package com.xof.phonecall.telecom

import android.Manifest
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Bundle
import android.provider.ContactsContract
import android.telecom.Call
import android.telecom.TelecomManager
import android.telephony.SubscriptionManager
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.vmadalin.easypermissions.EasyPermissions
import com.vmadalin.easypermissions.annotations.AfterPermissionGranted
import com.vmadalin.easypermissions.dialogs.DEFAULT_SETTINGS_REQ_CODE
import com.vmadalin.easypermissions.dialogs.SettingsDialog
import com.xof.phonecall.databinding.ActivityMainBinding
import com.xof.phonecall.extend.isAgreeLaunchPermissions
import com.xof.phonecall.receiver.PhoneCallBroadcastReceiver
import java.io.BufferedReader
import java.io.InputStreamReader


class MainActivity : AppCompatActivity(), EasyPermissions.PermissionCallbacks,
    EasyPermissions.RationaleCallbacks {

    private lateinit var mActivityBinding: ActivityMainBinding
    private lateinit var mPhoneCallBroadcastReceiver: PhoneCallBroadcastReceiver

    var sCall: Call? = null
    private var sIsAutoCalling = false
    private var sAutoCallingContactsList: List<ContactsContract.Contacts>? = null
    private var sAutoCallPosition = 0
    private val mSubscriptionManager: SubscriptionManager? = null
    private var mPermissionList: Array<String>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        mActivityBinding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(mActivityBinding.root)

        mPhoneCallBroadcastReceiver = PhoneCallBroadcastReceiver()
        mPhoneCallBroadcastReceiver.setActionListener { phoneCallState ->
            //读取日志
            println("读取日志")
//            getLogcatInfo()
        }
        val filter1 = IntentFilter("android.intent.action.PHONE_STATE")
        val filter2 = IntentFilter("android.intent.action.NEW_OUTGOING_CALL")
        registerReceiver(mPhoneCallBroadcastReceiver, filter1)
        registerReceiver(mPhoneCallBroadcastReceiver, filter2)

        requestLaunchPermissions()

        mActivityBinding.textCheckPermissions.setOnClickListener {
            if (isAgreeLaunchPermissions()) {
                Toast.makeText(this, "所有权限均开启", Toast.LENGTH_SHORT).show()
            } else {
                requestLaunchPermissions()
            }
        }

        mActivityBinding.textOutCall.setOnClickListener {
//            MyPhoneAccountManager.startCall("uid1234", "13113043327", "sky")
            MyCallManager.call(this, "13113043327")
        }

        mActivityBinding.textOutCallError.setOnClickListener {
//            MyPhoneAccountManager.startCall("uid1234", "13113043327", "sky")
            MyCallManager.call(this, "8484848484")
        }

        mActivityBinding.textIncomeCall.setOnClickListener {

        }

        mActivityBinding.textReadLogs.setOnClickListener {
//            readSysLog()
//            getLogcatInfo()
        }

        // Android M 以上的系统则发起将本应用设为默认电话应用的请求
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            println("Android M 以上的系统则发起将本应用设为默认电话应用的请求")
            val intent = Intent(TelecomManager.ACTION_CHANGE_DEFAULT_DIALER)
            intent.putExtra(
                TelecomManager.EXTRA_CHANGE_DEFAULT_DIALER_PACKAGE_NAME,
                packageName
            )
            startActivity(intent)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(mPhoneCallBroadcastReceiver)
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray,
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this)
    }

    override fun onRationaleAccepted(requestCode: Int) {
        mPermissionList?.let { list ->
            startEasyPermissions(list)
        }
    }

    override fun onRationaleDenied(requestCode: Int) {
    }

    override fun onPermissionsDenied(requestCode: Int, perms: List<String>) {
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            SettingsDialog.Builder(this).build().show()
        }
    }

    override fun onPermissionsGranted(requestCode: Int, perms: List<String>) {
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == DEFAULT_SETTINGS_REQ_CODE) {
            mPermissionList?.let { list ->
                startEasyPermissions(list)
            }
        }
    }

    @AfterPermissionGranted(100)
    fun onEasyPermissionsAllPassipetrpide() {
        Toast.makeText(this, "所有权限均开启", Toast.LENGTH_SHORT).show()
    }

    private fun requestLaunchPermissions() {
        try {
            startEasyPermissions(
                arrayOf(
                    Manifest.permission.READ_CONTACTS,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.READ_EXTERNAL_STORAGE,
                    Manifest.permission.READ_PHONE_STATE,
                    Manifest.permission.CALL_PHONE,
                    Manifest.permission.READ_PHONE_NUMBERS,
                    Manifest.permission.PROCESS_OUTGOING_CALLS
                )
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    protected fun startEasyPermissions(permissionList: Array<String>) {
        mPermissionList = permissionList

        EasyPermissions.requestPermissions(
            this,
            "Requie permissions",
            100,
            *permissionList
        )
    }

    private fun readSysLog() {
        var mIsRunning = true
        Thread {
            var process: Process? = null
            var bufferReader: BufferedReader? = null
            try {
                //清理日志
                Runtime.getRuntime().exec("logcat -c").waitFor();
                val cmd = "logcat -b system"
                process = Runtime.getRuntime().exec(cmd)
                bufferReader = BufferedReader(InputStreamReader(process.inputStream))
                var line: String? = bufferReader.readLine()
                while (line != null) {
                    println(line)
                    line = bufferReader.readLine()
                    runOnUiThread {
                        var tempText = mActivityBinding.tvLog.text.toString().trim()
                        tempText += "\n"
                        tempText += line
                        mActivityBinding.tvLog.text = tempText
                    }
                }
            } catch (e: Exception) {
            } finally {
                if (bufferReader != null) {
                    bufferReader.close();
                }
                if (process != null) {
                    process.destroy();
                }
            }
        }.start()
    }

    private fun getLogcatInfo(): String {
        val strLogcatInfo: String = ""
        try {
            val commandLine: MutableList<String> = mutableListOf()
            commandLine.add("logcat")
            commandLine.add("-d")

            commandLine.add("*:E") // 过滤所有的错误信息

            val clearLog: MutableList<String> = mutableListOf()  //logcat -c 清除日志
            clearLog.add("logcat");
            clearLog.add("-c");

            val process: Process = Runtime.getRuntime().exec(commandLine.toTypedArray())
            val bufferReader = BufferedReader(InputStreamReader(process.inputStream))

            var line: String? = bufferReader.readLine()
            println(line)
            while (line != null) {
                println(line)
                Runtime.getRuntime().exec(clearLog.toTypedArray())
                line = bufferReader.readLine()
//                runOnUiThread {
//                    var tempText = mActivityBinding.tvLog.text.toString().trim()
//                    tempText += "\n"
//                    tempText += line
//                    mActivityBinding.tvLog.text = tempText
//                }
            }
//            bufferReader.close()

        } catch (e: Exception) {
            e.printStackTrace()
        }
        return strLogcatInfo;
    }
}